package com.betty.cscams.service.impl;

import com.betty.cscams.common.page.MybatisPageHelper;
import com.betty.cscams.common.page.PageRequest;
import com.betty.cscams.common.page.PageResult;
import com.betty.cscams.dao.PsyAnswerMapper;
import com.betty.cscams.dao.PsyScoreMapper;
import com.betty.cscams.entity.PsyAnswer;
import com.betty.cscams.entity.PsyScore;
import com.betty.cscams.service.PsyAnswerService;
import com.betty.cscams.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * ---------------------------
 *  心理测评答题记录Service实现类(PsyAnswerServiceImpl)         
 * ---------------------------
 */
@Service
public class PsyAnswerServiceImpl implements PsyAnswerService {

    @Autowired
    private PsyAnswerMapper psyAnswerMapper;
    
    @Autowired
    private PsyScoreMapper psyScoreMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(PsyAnswer record) {
        record.setLastUpdateBy(SecurityUtils.getUsername());
        record.setLastUpdateTime(new Date());
        if(record.getId() == null || record.getId() == 0) {
            // 新增记录
            record.setCreateBy(SecurityUtils.getUsername());
            record.setCreateTime(new Date());
            record.setDelFlag(0);
            return psyAnswerMapper.add(record);
        }
        return psyAnswerMapper.update(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(PsyAnswer record) {
        return psyAnswerMapper.delete(record.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(List<PsyAnswer> records) {
        for(PsyAnswer record : records) {
            delete(record);
        }
        return 1;
    }

    @Override
    public PsyAnswer findById(Long id) {
        return psyAnswerMapper.findById(id);
    }

    @Override
    public PageResult findPage(PageRequest pageRequest) {
        // 答题记录通常不需要分页查询，这里提供一个空实现
        return new PageResult();
    }

    @Override
    public List<PsyAnswer> findByStudentAndTerm(String studentNum, Long termId) {
        return psyAnswerMapper.findByStudentAndTerm(studentNum, termId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveAnswers(List<PsyAnswer> answers, String studentNum, Long termId) {
        if(answers == null || answers.isEmpty()) {
            return 0;
        }
        
        // 1. 删除该学生本学期的所有答题记录
        psyAnswerMapper.deleteByStudentAndTerm(studentNum, termId);
        
        // 2. 设置通用字段并批量保存答题记录
        Date now = new Date();
        String username = SecurityUtils.getUsername();
        
        for(PsyAnswer answer : answers) {
            answer.setStudentNum(studentNum);
            answer.setTermId(termId);
            answer.setCreateBy(username);
            answer.setCreateTime(now);
            answer.setLastUpdateBy(username);
            answer.setLastUpdateTime(now);
            answer.setDelFlag(0);
        }
        
        psyAnswerMapper.batchAdd(answers);
        
        // 3. 计算总分并保存到成绩表
        BigDecimal totalScore = BigDecimal.ZERO;
        for(PsyAnswer answer : answers) {
            if(answer.getScore() != null) {
                totalScore = totalScore.add(answer.getScore());
            }
        }
        
        // 查询是否已存在成绩记录
        PsyScore score = psyScoreMapper.findByStudentAndTerm(studentNum, termId);
        if(score == null) {
            // 不存在则新增
            score = new PsyScore();
            score.setStudentNum(studentNum);
            score.setTermId(termId);
            score.setTotalScore(totalScore);
            score.setStatus(1); // 已完成状态
            score.setCreateBy(username);
            score.setCreateTime(now);
            score.setLastUpdateBy(username);
            score.setLastUpdateTime(now);
            score.setDelFlag(0);
            psyScoreMapper.add(score);
        } else {
            // 存在则更新
            score.setTotalScore(totalScore);
            score.setStatus(1); // 已完成状态
            score.setLastUpdateBy(username);
            score.setLastUpdateTime(now);
            psyScoreMapper.update(score);
        }
        
        return answers.size();
    }
} 